using AutoMapper;
using MediatR;
using ThreeTeams.Domain.ThreeTeams.Domain.Entities;
using WMS.Api.Application.Commands;
using WMS.Common;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers
{
    /// <summary>
    /// 获取产品详情命令处理程序
    /// </summary>
    public class GetProductByIdCommandHandler : IRequestHandler<GetProductByIdCommand, ApiResult<ProductDto>>
    {
        private readonly IBaseRepository<Product> _productRepository;
        private readonly IMapper _mapper;

        public GetProductByIdCommandHandler(IBaseRepository<Product> productRepository, IMapper mapper)
        {
            _productRepository = productRepository;
            _mapper = mapper;
        }

        public async Task<ApiResult<ProductDto>> Handle(GetProductByIdCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ProductDto>("获取产品详情");

            try
            {
                var product = await _productRepository.GetValueByIdAsync(request.Id);

                if (product == null)
                {
                    result.code = StatusCodeEnum.DataNotExist;
                    result.msg = "产品不存在";
                    return result;
                }

                var productDto = _mapper.Map<ProductDto>(product);
                result.Success(productDto);
            }
            catch (Exception ex)
            {
                result.code = StatusCodeEnum.Fail;
                result.msg = $"获取产品详情失败：{ex.Message}";
            }

            return result;
        }
    }
} 